﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization.Json;
using System.IO;

namespace FC.Utils
{
    public static class JsonHelper
    {
        /// <summary>
        /// 将 JSON（JavaScript 对象表示法）格式的字符串反序列化为 T 类型的对象
        /// </summary>
        /// <typeparam name="T">返回对象类型</typeparam>
        /// <param name="json">JSON（JavaScript 对象表示法）格式的字符串</param>
        /// <returns></returns>
        public static T ToClass<T>(this string json) where T : class
        {
            T model = null;
            try
            {
                using (MemoryStream stream = new MemoryStream(Encoding.Unicode.GetBytes(json)))
                {
                    DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(T));
                    var temp = jsonSerializer.ReadObject(stream);
                    model = (T)temp;// //反序列化ReadObject
                }
            }
            catch (Exception)
            {

            }
            return model;
        }

        /// <summary>
        /// 将指定对象序列化为 JavaScript 对象表示法 (JSON) 数据字符串
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="obj">对象</param>
        /// <returns></returns>
        public static string ToJson<T>(this T obj) where T : class
        {
            string json = null;
            DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(T));
            using (MemoryStream stream = new MemoryStream())
            {
                //将序列化之后的Json格式数据写入流中
                jsonSerializer.WriteObject(stream, obj);
                //从0这个位置开始读取流中的数据
                stream.Position = 0;
                using (StreamReader sr = new StreamReader(stream, Encoding.UTF8))
                {
                    json = sr.ReadToEnd();
                }
            }
            return json;
        }
    }
}
